<?php
class TransferForm extends CFormModel
{
	public $to;
	public $amount = 0;
	public $verifyCode;


	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__){
		return parent::model($className);
	}
	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			array('amount', 'required', 'message' => Yii::t('msg', '0030')),
			array('amount', 'type','type' => 'integer', 'message' => Yii::t('msg', '0032')),
			array('to','checkTo'),
			array('amount','checkAmount'),
			array('to', 'required', 'message' => Yii::t('msg', '0031')),
			array('verifyCode', 'application.validators.CaptchaAjax'),
		);
	}

	public function checkTo($attribute, $params){
		if($this->$attribute == Yii::app()->user->getState('current_user')->code){
			$this->addError('to', Yii::t('msg', '0034'));
			return false;
		}
		$check = User::model()->countByAttributes(array('code' => $this->$attribute));
		if($check <= 0){
			$this->addError('to', Yii::t('msg', '0033'));
			return false;
		}
		return true;
	}

	public function checkAmount($attribute, $params){
		$min_transfer = Setting::model()->getValueSetting('setting','min_transfer');
		$transfer_rate = Setting::model()->getValueSetting('setting','transfer_rate');
		$final_coin = $this->$attribute + ceil($this->$attribute * ($transfer_rate/100));
		$current_user = User::model()->findByPk(Yii::app()->user->getState('current_user')->id);
		if($final_coin < $min_transfer){
			$this->addError('amount', Yii::t('msg', '0037', array('{min_transfer}' => $min_transfer)));
			return false;
		}
		if($current_user->amount < $final_coin){
			$this->addError('amount', Yii::t('msg', '0038', array('{total}' => $final_coin)));
			return false;			
		}
		return true;
	}


	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'amount'=> Yii::t('lbl', '0017', array()),
			'to'=> Yii::t('lbl', '0016', array()),
			'verifyCode'=> Yii::t('lbl', '0008', array()),
		);
	}
}
